﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace PmSoft.Core.Job.Timer;

/// <summary>
/// Timer 作业执行包装器，负责定时执行作业
/// </summary>
public class TimerJobExecutor : JobExecutionWrapper
{
	private readonly Type _jobType;
	private System.Threading.Timer _timer;

	/// <summary>
	/// 构造函数，初始化作业类型
	/// </summary>
	/// <param name="scopeFactory">服务作用域工厂</param>
	/// <param name="logger">日志记录器</param>
	/// <param name="jobType">作业类型</param>
	public TimerJobExecutor(IServiceScopeFactory scopeFactory, ILogger<JobExecutionWrapper> logger, Type jobType)
		: base(scopeFactory, logger)
	{
		_jobType = jobType;
	}

	/// <summary>
	/// 启动定时器
	/// </summary>
	/// <param name="intervalSeconds">执行间隔（秒）</param>
	public void Start(int intervalSeconds)
	{
		_timer = new System.Threading.Timer(async _ => await ExecuteJob(_jobType), null, 0, intervalSeconds * 1000);
	}

	/// <summary>
	/// 停止定时器，释放资源
	/// </summary>
	public void Stop()
	{
		_timer?.Dispose();
	}
}
